<?php
/**
 * User: LazyCat
 * Date: 2017/7/12
 * Time: 16:50
 */
namespace app\index\logic;

use think\Db;
use  app\index\model\Essay;

class EssayLogic{
    public static function self(){
        return new self;
    }

    public function getSelfAllEssays($uid)
    {
        $result = Essay::self()->getEssaysByUid($uid);
        $result = $this->judgeImgIsNull($result);
        if(!empty($result)){
            $result = $result->toArray();
        }
        return $result;
    }

    public function getEssayInfo($eid)
    {
        $essay_info = Db::name('essay')->where(['eid'=>$eid])->find();
        if(!empty($essay_info)){
            $essay_info = judgeImgIsNull($essay_info);
            $essay_info['create_time'] = friendlyDate(strtotime($essay_info['create_time']), 'normal');
            $essay_info['two_comments'] = EssayCommentLogic::self()->getEssayCommentList($essay_info['eid'],0,1,2);
            $user_info = Db::name('user')->field('nickname,avatar')->where(['id'=>$essay_info['uid']])->find();
//
            $essay_info['nickname'] = $user_info['nickname'];
//            $essay_info['avatar'] = "http://shikenote-img.oss-cn-hangzhou.aliyuncs.com/9365DBA0-1888-4C2A-96FD-C402F73148EE.jpg";
//            $essay_info['avatar'] = $user_info['avatar'];
            $essay_info['avatar'] = $user_info['avatar'];
        }

        return $essay_info;
    }

    public function delEssay($eid,$uid){
        $result = Essay::self()->delEssayByEid($eid,$uid);
        if($result){
            return true;
        }else{
            return false;
        }
    }

    public function addEssay($user,$data,$validate_img_url = false)
    {
        if(!empty($user)){
            $data['uid'] = $user['id'];
        }else{
            $data['uid'] = 0;
        }
        $time = time();
        $data['create_time'] = date('Y-m-d H:i:s',$time);
        $result = Essay::self()->addEssay($data,$validate_img_url);
        if($result){
            return date('m/d',time());
        }else{
            return false;
        }
    }

    public function likeEssay($eid,$user)
    {
        $res = [
            'status' => true,
            'msg' => ''
        ];
        //判断是否已点赞
        $result_is_like = Essay::self()->getEssayLikeLog(['eid'=>$eid,'uid'=>$user['id']]);
        if($result_is_like){
            $res['status'] = false;
            $res['msg'] = '您已点赞';
            return $res;
        }
        // @step1 修改essay信息
        $result1 = Essay::self()->modifyEssayInfoIncOrDec($eid,'like_count',true);
        // @step2 修改点赞记录
        $result2 = Essay::self()->essayLikeLog($eid,$user['id'],'like');
        // @step3 修改个人信息
        User::self()->changeUserAttr($user['id'],'like_count',1);

        if($result1){
            $res['msg'] = $result1->like_count;
        }else{
            $res['status'] = false;
            $res['msg'] = '网络错误，请稍后重试';
        }
        return $res;

//        // @step1 修改essay信息
//        $result1 = Essay::self()->modifyEssayInfoIncOrDec($eid,'like_count',true);
//
//        if($result1){
//            // @step2 修改点赞记录
//            $result2 = Essay::self()->essayLikeLog($eid,$user['id'],'like');
//            // @step3 修改个人信息
//            User::self()->changeUserAttr($user['id'],'like_count',1);
//            return $result1['like_count'];
//        }else{
//            return false;
//        }
    }

    public function dislikeEssay($eid,$user)
    {
        // @step1 删除点赞记录
        $result1 = Essay::self()->deleteEssayLikeLog($eid,$user['id']);
        if($result1){
            // @step1 修改essay信息
            $result2 = Essay::self()->modifyEssayInfoIncOrDec($eid,'like_count',false);
            // @step3 修改个人属性信息
            User::self()->changeUserAttr($user['id'],'like_count',0);
            return true;
        }else{
            return false;
        }
    }

    public function getEssayList($where = [],$page = 1,$limit = 10)
    {
        $essay_list = Essay::self()->getEssayList($where,$page,$limit);
        foreach ($essay_list as $key=>$essay){
            $essay_list[$key]['create_time'] = friendlyDate(strtotime($essay['create_time']), 'normal');
            $essay_info[$key]['two_comments'] = EssayCommentLogic::self()->getEssayCommentList($essay['eid'],$where['uid'],1,2);
        }
        $essay_list = $this->judgeImgIsNull($essay_list);
        if($essay_list){
            $essay_list = Essay::self()->judgeEssayIsLike($where['uid'],$essay_list);
            return $essay_list;
        }else{
            return [];
        }
    }

    public function getEssayFocusList($user,$uid,$page,$limit)
    {
        $essay_info = Essay::self()->getEssayFocusList($uid,$page,$limit,$user['id']);
        $essay_info = $this->judgeImgIsNull($essay_info);
        foreach ($essay_info as $key=>$value){
            $essay_info[$key]['create_time'] = friendlyDate(strtotime($value['create_time']), 'normal');

            if($value['uid']){
                $user_info = User::self()->findUser($value['uid']);
                $essay_info[$key]['nickname'] = $user_info['nickname'];
                $essay_info[$key]['avatar'] = $user_info['avatar'];
            }else{
                $essay_info['nickname'] = '';
                $essay_info['avatar'] = '';
            }
            $essay_info[$key]['two_comments'] = EssayCommentLogic::self()->getEssayCommentList($value['eid'],$uid,1,2);
        }
        $essay_info = Essay::self()->judgeEssayIsLike($user['id'],$essay_info);
        $essay_info = Essay::self()->judgeEssayCreatorIsFan($uid,$essay_info);
        return $essay_info;
    }

    public function getEssayRandomList($user,$page,$limit)
    {
        $essay_info = Essay::self()->getEssayRandomList($page,$limit);
        $essay_info = $this->judgeImgIsNull($essay_info);
        //判断简记是否是被关注的
        if(empty($user)){
            $uid = '';
        }else{
            $uid = $user['id'];
        }
        $essay_info = Essay::self()->judgeEssayIsLike($uid,$essay_info);
        foreach ($essay_info as $key=>$value){
            $essay_info[$key]['create_time'] = friendlyDate(strtotime($value['create_time']), 'normal');
            $essay_info[$key]['two_comments'] = EssayCommentLogic::self()->getEssayCommentList($value['eid'],$uid,1,2);
        }
        //判断简记的人是否是被关注的
        $essay_info = Essay::self()->judgeEssayCreatorIsFan($uid,$essay_info);
//        echo count($essay_info);exit;
        return $essay_info;
    }

    public function searchEssay($uid,$keyword,$page,$limit)
    {
        if(empty($keyword)){
            return [];
        }
        $essay_list = Essay::self()->searchEssay($keyword,$page,$limit);
        $essay_list = $this->judgeImgIsNull($essay_list);
        if(empty($essay_list)){
            return [];
        }else{
            foreach($essay_list as $key=>$value){
                $essay_list[$key]['create_time'] = friendlyDate(strtotime($value['create_time']), 'normal');
                if($value['uid']){
                    $user_info = User::self()->findUser($value['uid']);
                    $essay_list[$key]['nickname'] = $user_info['nickname'];
                    $essay_list[$key]['avatar'] = $user_info['avatar'];
                }else{
                    $essay_list['nickname'] = '';
                    $essay_list['avatar'] = '';
                }
            }
            $essay_list = Essay::self()->judgeEssayCreatorIsFan($uid,$essay_list);


            $essay_list = Essay::self()->judgeEssayIsLike($uid,$essay_list);

        }

        return $essay_list;
    }

    public function reportEssay($uid,$eid)
    {
        $result = [
            'status' => false,
            'msg' => ''
        ];
        // @step1 是否已举报过
        $res = Essay::self()->getEssayReport(['uid'=>$uid,'eid'=>$eid]);
        // @step2 没有，则添加举报记录
        if(!$res){
            $essay_info = Essay::self()->getEssayInfoByEid($eid);
            $rs = Essay::self()->addEssayReport($uid,$eid,$essay_info['uid']);
            if($rs){
                $result['status'] = true;
            }else{
                $result['msg'] = '操作失败，请稍后再试';
            }
        }else{
            $result['msg'] = '您已举报当前用户，请高抬贵手哦';
        }

        return $result;
    }

    public function judgeImgIsNull($essay)
    {
        if(empty($essay)){
            return $essay;
        }
        if(is_mul_array($essay)){
            foreach ($essay as $key=>$value){
                if(!$value['img_url']){
                    $essay[$key]['img_url'] = [];
                }else{
                    $essay[$key]['img_url'] = json_decode($value['img_url'],true);
                }
            }
        }else{
            if(!$essay['img_url']){
                $essay['img_url'] = [];
            }else{
                $essay['img_url'] = json_decode($essay['img_url'],true);
            }
        }
        return $essay;
    }

    public function getRecUserList()
    {
        $user = User::self()->getUserList();
        return $user;
    }

    public function addEssayReward($uid,$eid,$reward_id)
    {
        //code 0 是正确的
        $return = [
            'status' => false,
            'code' => 1
        ];
        $essay_info = Essay::self()->getEssayInfoByEid($eid);
        if(!$essay_info){
            return $return;
        }
        $target_uid = $essay_info['uid'];
        $config_reward = config('reward_list');
        $money = $config_reward[$reward_id]['money'];
        $user_info = db('user')->where(['id'=>$uid])->find();
        if($user_info['balance'] < $money){
            $return['code'] = 2; //余额不足
            return $return;
        }
        Db::startTrans();
        try{
            // 添加 essay_rewards
            $res = Db::name('essay_rewards')->insert([
                'eid' => $eid,
                'uid' => $uid,
                'target_uid' => $target_uid,
                'reward_id' => $reward_id,
                'money' => $money,
                'create_time' => date('Y-m-d H:i:s',time())
            ]);
            // 增加 essay 的 reward
            Db::name('essay')->update([
                'eid' => $eid,
                'reward' => $essay_info['reward'] + $money
            ]);
            //增加target_uid 的 balance
            Db::name('user')->update([
                'id' => $target_uid,
                'balance' => ['exp','balance+'.$money]
            ]);
            // 减少 uid 的 balance
            Db::name('user')->update([
                'id' => $uid,
                'balance' => ['exp','balance-'.$money]
            ]);
            UserLogic::self()->createUserMsg($target_uid,$uid,2,$eid,0,' '.$money.'元');

            // 发送消息
            // 提交事务
            Db::commit();
            $return['status'] = true;
            return $return;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $return['code'] = 1;
            return false;
        }

    }

}